package com.ityu.filter;

import com.ityu.utlis.CurrentHolder;
import com.ityu.utlis.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (!StringUtils.hasLength( token)){
            log.info("-----TokenInterceptor-----token为空！");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        try {
            Claims claims = JwtUtils.parseJWT(token);
            CurrentHolder.setCurrentId(Integer.parseInt(claims.get("id").toString()));

        } catch (Exception e) {
            log.info("-----TokenInterceptor-----token解析失败！");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        CurrentHolder.remove();
        return true;
    }
}
